import React from 'react';

import { Link } from 'react-router';
import { connect } from 'react-redux';

import Portals from '../components/portals';
import Brandings from '../components/brandings';
import Channels from '../components/channels';
import Banners from '../components/Banners';
//import HotArticle from '../components/HotArticle';
import Articles from '../components/Articles';
import Loadmore from '../components/LoadMore';

import { fetchHomeData, switchChannel, initHomeArticles } from '../actions/home';
import { fetchArticle } from '../actions/article';
import NormalHeaderBar from '../components/NormalHeaderBar';
import { hashHistory } from 'react-router';
import getCookieName from '../utils/cookieHelper';
import axios from 'axios';
import Picker from '../components/picker';
import { API_ROOT } from '../config.jsx';

class HomePage extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            sort: "0"
        }
    }

    componentDidMount() {
        let token = getCookieName("token");

        if (token !== undefined ) {
            this.props.fetchHomeData(token);
        } else {
            hashHistory.push('500error');
        }

        var _this = this;

        axios.defaults.headers.common['Authorization'] = sessionStorage.token;
        const articles = axios.get(`${API_ROOT}/wechatapi/Articles/-1/1/0`).then(function(articlesRes){
            var articles = articlesRes.data.articles;
            var page = articlesRes.data.page;
            var pageCount = articlesRes.data.pageCount;
            
            _this.props.initHomeArticles(articles, page, pageCount);
        });
        
        
    }

    handleSwitchChannel(channelId) {
        hashHistory.push('articles/'+channelId+'/1/0');
    }

    handleLoad(page) {
        //this.props.loadMoreArticle(this.props.params.channel, page, 0);
        //hashHistory.push('articles/'+this.state.channel+'/'+ page +'/'+0);

        var _this = this;
        var id = this.state.sort;
        axios.defaults.headers.common['Authorization'] = sessionStorage.token;
        const articles = axios.get(`${API_ROOT}/wechatapi/Articles/-1/${page}/${id}`).then(function(articlesRes){
            var articles = articlesRes.data.articles;
            var page = articlesRes.data.page;
            var pageCount = articlesRes.data.pageCount;
            
            _this.props.initHomeArticles(articles, page, pageCount);
            window.scrollTo(0,0);
        });
    }

    sortHandler(id) {
        this.setState({
            sort: id
        });

        var _this = this;
        axios.defaults.headers.common['Authorization'] = sessionStorage.token;
        const articles = axios.get(`${API_ROOT}/wechatapi/Articles/-1/1/${id}`).then(function(articlesRes){
            var articles = articlesRes.data.articles;
            var page = articlesRes.data.page;
            var pageCount = articlesRes.data.pageCount;
            
            _this.props.initHomeArticles(articles, page, pageCount);
        });
        
        //this.props.switchChannel(this.state.channel, 1, id);
        //hashHistory.push('articles/'+this.state.channel+'/1/'+id);
    }
 
    render() {
        var settings = {
            dots: true,
            infinite: true,
            speed: 500,
            slidesToShow: 1,
            slidesToScroll: 1
        };

        if (this.props.portals == null || this.props.portals.length <= 0) {
            return (<div>Loading...</div>);
        } else {
            var _this = this;
            let portal = this.props.portals[0];
            let brandings = this.props.brandings;
            let channels = [];
            let banners = [];
            //let hots = []
            if (this.props.channels.length > 6) {
                channels = this.props.channels.slice(0, 6);
                banners = this.props.channels.slice(6, this.props.channels.length);
            } else {
                channels = this.props.channels;
            }
            
            /*if (this.props.hots.length > 0) {
                hots = this.props.hots;
            }*/

            let articles = [];
            let articleDiv = (<div></div>);
            if (this.props.articles !== undefined && this.props.articles.length > 0) {
                articles = this.props.articles;
                articleDiv = (<Articles articles={articles}/>)
            }
            let topMenu1 = {
                width: "calc(100% / 3)",
                float: "left",
                height: "2rem",
                marginTop: "1rem",
                fontSize: "0.8rem",
                color: "rgb(114,124,174)",
                textAlign: "center"
            };
            let topMenu2 = {
                width: "calc(100% / 3)",
                float: "left",
                height: "2rem",
                marginTop: "1rem",
                fontSize: "0.8rem",
                color: "rgb(114,124,174)",
                textAlign: "center"
            };
            let topMenu3 = {
                width: "calc(100% / 3)",
                float: "left",
                height: "2rem",
                marginTop: "1rem",
                fontSize: "0.8rem",
                color: "rgb(114,124,174)",
                textAlign: "center"
            };
            
            switch (this.state.sort) {
                case "0":
                    topMenu1.borderBottom = "3px solid #fff";
                    topMenu1.color = "#fff";
                    break;
                case "1":
                    topMenu2.borderBottom = "3px solid #fff";
                    topMenu2.color = "#fff";
                    break;
                case "2":
                    topMenu3.borderBottom = "3px solid #fff";
                    topMenu3.color = "#fff";
                    break;
            }
            // {banners && banners.length > 0 && <Banners banners={banners} handleSwitchChannel={this.handleSwitchChannel.bind(this)} />}
            return (
                <div>
                    <NormalHeaderBar title={ portal.Name } toSearch="search" showReview={'1'}/>
                    <Brandings brandings={ brandings }/>
                    <Channels channels={channels} handleSwitchChannel={this.handleSwitchChannel.bind(this)} />
                   
                    <div style={{height: "3rem",backgroundColor: "rgb(66,79,164)"}}>
                        <div style={topMenu1} onClick={() => { this.sortHandler("0") } }>最新发布</div>
                        <div style={topMenu2} onClick={() => { this.sortHandler("1") } }>最热门话题</div>
                        <div style={topMenu3} onClick={() => { this.sortHandler("2") } }>最多点评</div>
                    </div>
                    { articleDiv }
                    { articles.length > 0 && <Loadmore page={this.props.page} defaultPageSize={articles.length} pageCount={(articles.length * this.props.pageCount)} handleLoad={this.handleLoad.bind(this)} pageChange={this.handleLoad.bind(this)}/>}
                </div>
            );
        }
    }
}

function mapStateToProps(state) {
    return {
        portals: state.home.portals,
        channels: state.home.channels,
        brandings: state.home.brandings,
        articles: state.home.articles,
        pageCount: state.home.pageCount,
        page: state.home.page
    };
}

export default connect(mapStateToProps, { fetchHomeData, switchChannel, fetchArticle, initHomeArticles })(HomePage);